<template>
	<view>
		<u-navbar title="个人头像" :border-bottom="false"></u-navbar>
		<view style="width: 100%;padding: 30% 20rpx;text-align: center;color: #909399;">
			<avatar ref='avatar' selWidth="600upx" selHeight="600upx" @upload="myUpload" 
			:avatarSrc="vuex_userInfo.avatar?vuex_userInfo.avatar:useravatar"
				avatarStyle="width:500upx; height: 500upx;">
			</avatar>
			<view>点击更新头像</view>
		</view>
	</view>
</template>

<script>
	import avatar from "@/components/yq-avatar/yq-avatar.vue";
	export default {
		components: {
			avatar
		},
		data() {
			return {
				background: {
					backgroundColor: '#000000',
				},
				useravatar:'',
			};
		},
		methods: {
			//上传返回图片
			myUpload(rsp) {
				 let uploadFileUrl = this.$u.api.multipartAddress.updload;
				let obj = {
					type: "img",
					filePath: rsp.path,
					uploadUrl: uploadFileUrl+"&dir=userAvatars"  //自己的服务器
				}
				this.uploadFile(obj);
			},
			uploadFile: function(tempFileInfo) {
				let that = this;
				let target = that.$u.api.multipartAddress.target;
				const uploadTask = uni.uploadFile({
					url: tempFileInfo.uploadUrl,
					filePath: tempFileInfo.filePath,
					name: 'fileName',
					header: {
						'Access-Control-Allow-Origin': '*',
						'TOKEN_IM': that.vuex_token,
					},
					success: (uploadFileRes) => {
						if (uploadFileRes.statusCode == 200 && uploadFileRes.data.length > 0) {
							let resObj = JSON.parse(uploadFileRes.data);
							if (resObj.code == 200) {
								let fileInfo = resObj.data;
								console.log("上传头像响应结果",fileInfo);
								let fullPath=fileInfo.fullPath;
								let fileName=fileInfo.fileName;
								let imageSrc="";
								if(target=="local"){
									imageSrc=that.$u.api.multipartAddress.showFile+fullPath;
								}
								else{
									imageSrc=fullPath;
								}
								that.$u.vuex('vuex_userInfo.avatar',imageSrc);
								that.useravatar=imageSrc;
								that.updateUserInfo();
								console.log("更新头像", imageSrc);
							} else {
								console.log("文件上传失败");
							}
						} else {
							console.log("文件上传失败");
						}
					},
					fail: function() {
						console.log("文件上传失败");
					},
					complete: function() {
						uni.hideLoading();
					}
				});
			},
			updateUserInfo:function(){
				let that=this;
				let param=that.vuex_userInfo;
				param.avatar=that.useravatar;
				that.$u.api.imUser.updateUserInfo(param).then(res => {
					if(res.code==200){
						console.log("修改用户头像结果，此时可以缓存到本地去",res);
					}
				})
			},
		}
	}
</script>

<style lang="scss">
	page {
		// background-color: #000000;
	}
</style>
